package com.foxzzz.command;

import com.foxzzz.config.Configration;
import com.foxzzz.operation.InitDataBaseOperation;
import org.bukkit.entity.Player;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CmdHandler {
    private static Map<String, Method> methodMap = new ConcurrentHashMap<String, Method>();
    private static Map<String, Commands> commandsMap = new ConcurrentHashMap<String, Commands>();
    public static Configration configration=new Configration();
    private static ExecutorService threadPool= Executors.newCachedThreadPool();

    static {
        Method[] methods = Commands.class.getDeclaredMethods();
        for (Method method : methods) {
            methodMap.put(method.getName(),method);
        }
    }

    public static String execute(Player p, String method, String... args) {
        String methodName = method.toLowerCase().trim();
        String player=p.getName();
        Method m =  methodMap.get(methodName);
        Commands commands = null;
        if (!commandsMap.keySet().contains(player))
           commandsMap.put(player,new Commands(p));
        commands = commandsMap.get(player);
        Object ret=null;
        try {
           ret=m.invoke(commands,args);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret==null?null:ret.toString();
    }

    //开启线程执行
    public static void exec(Player p,String method,String... args){
        final Player tempP=p;
        final String tempMethod=method;
        final String[] tempArgs=args;
        threadPool.execute(new Runnable() {
            public void run() {
               String result=execute(tempP,tempMethod,tempArgs);
               tempP.sendMessage(result);
            }
        });

    }

}
